package com.cbs.android.function.imagepick;

import android.content.Intent;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.handler.CBSActivityResultHandler;

import java.lang.ref.WeakReference;

/**
 * Created by broche on 07/11/2016.
 */

public class ImagePickFunction {
    private static final int REQUEST_IMAGEPICK = 0xFFCA;

    public interface Extras {
        String Count = "count";
        String Result = "result";
    }

    public static void start(CBSActivity activity, ImagePickHandler handler) {
        start(activity, 1, handler);
    }

    public static void start(CBSActivity activity, int count, ImagePickHandler handler) {
        activity.addActivityResultHandler(new MyActivityResultHandler(activity, handler));
        Intent intent = new Intent(activity, ImagePickActivity.class);
        intent.putExtra(Extras.Count, count);
        activity.startActivityForResult(intent, REQUEST_IMAGEPICK);
    }

    private static class MyActivityResultHandler implements CBSActivityResultHandler {
        private final WeakReference<CBSActivity> activity;
        private final CBSActivityResultHandler handler;

        public MyActivityResultHandler(CBSActivity activity, CBSActivityResultHandler handler) {
            this.activity = new WeakReference<>(activity);
            this.handler = handler;
        }

        @Override
        public void onActivityResult(int requestCode, int responseCode, Intent intent) {
            if (requestCode == REQUEST_IMAGEPICK) {
                if (handler != null) {
                    handler.onActivityResult(requestCode, responseCode, intent);
                }
                if (activity != null && activity.get() != null) {
                    activity.get().removeActivityResultHandler(this);
                }
            }
        }
    }
}
